<?php
declare (strict_types=1);

namespace App\Http\controllers;

use App\Models\CollectStoreModel;
use App\Models\ShopCartModel;
use App\Models\ShopModel;
use App\Models\ShopTypeModel;
use App\Models\SlideshowModel;
use App\Sevrice\ApiJwt;
use App\Sevrice\Es;
use App\Sevrice\handleLog;
use App\Sevrice\ObServer1;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ShopController
{
    /**
     * @return mixed
     * 查询商品分类信息
     */
    function shopTypeInfo()
    {
        $data = ShopTypeModel::get()->toArray();
        Redis::zincrby('one', 1, json_encode($data));
        return $data;
    }

    /**
     * @return mixed
     * 轮播图
     */
    function slideshow()
    {

        if(Cache::get('slide')){
            return Cache::get('slide');
        }
        $data = SlideshowModel::orderByRaw('sort_num', 'desc')->limit(5)->get();
        Cache::set('slide',$data);
        return $data;
    }

    /**
     * @param Request $request
     * @return mixed
     * 查询商品信息
     */
    function shopInfoList(Request $request)
    {
        $shopTid = $request->post('shopTid');
        $shopNick = $request->post('searchVal');
        $data = ShopModel::join('shop_type', 'shop_tid', 'tid')
            ->where(function ($query) use ($shopNick, $shopTid) {
                if ($shopNick) {
                    $query->where('shop_nick', "like", "%$shopNick%");
                }
                if ($shopTid) {
                    $query->where('shop_tid', $shopTid);
                }
            })->select(['shop_id', 'shop_nick', 'shop_logo', 'shop_price'])->paginate(8)->toArray();
        $arr = [];
        foreach ($data['data'] as $v) {
            $v['shop_nick'] = str_replace($shopNick, "<span style='color:red'>$shopNick</span>", $v['shop_nick']);
            $one = explode(',', $v['shop_logo']);
            $index = mt_rand(0, (count($one) - 1));
            $v['shop_logo'] = $one[$index];
            array_push($arr, $v);
        }
        $data['data'] = $arr;
        return $data;
    }

    /**
     * @param Request $request
     * @return array
     *查询商品详细信息
     */
    function shopInfo(Request $request)
    {
        $shopId = $request->get('shopId');
        if(Cache::get($shopId)){
            return Cache::get($shopId);
        }
        $userId = ApiJwt::decodeToken($request->header('token'));
        $dataInfo = ShopModel::with('storeInfo')->where('shop_id', $shopId)->first()->toArray();
        //将添加、修改时间由2022-08-25T20:03:46.000000Z格式替换成2022-08-25 20:03:46标准时间格式
        $dataInfo['created_at'] = substr($dataInfo['created_at'], 0, 10) . ' ' . substr($dataInfo['created_at'], 11, 8);
        $dataInfo['updated_at'] = substr($dataInfo['created_at'], 0, 10) . ' ' . substr($dataInfo['created_at'], 11, 8);
        $dataInfo['shop_logo'] = explode(',', $dataInfo['shop_logo']);
        $dataInfo['store_name'] = $dataInfo['store_info']['store_name'];
        $dataInfo['cartNum']=array_sum(ShopCartModel::where('user_num',$userId)->pluck('shop_count')->toArray());
        unset($dataInfo['store_info']);
        $collect = CollectStoreModel::where('user_num', $userId)->where('shop_num', $dataInfo['shop_name'])->value('collect_id');
        if ($collect) {
            $dataInfo['is_collect'] = 0;
        } else {
            $dataInfo['is_collect'] = 1;
        }
        handleLog::handleLog($userId,$shopId);//日志记录用户浏览足迹
        Cache::set($shopId,$dataInfo);
        return $dataInfo;
    }

    /**
     * @param Request $request
     * @return array
     * 收藏店铺
     */
    function collectShop(Request $request)
    {
        $arr['shop_num'] = $request->post('store_id');
        $arr['user_num'] = ApiJwt::decodeToken($request->header('token'));
        $arr['created_at'] = date('YmdHis');
        $res = CollectStoreModel::insertGetId($arr);
        if ($res) {
            return ['code' => 200, 'msg' => '收藏成功'];
        }
        return ['code' => 400, 'msg' => '收藏失败'];
    }

    /**
     * @param Request $request
     * @return array
     * 取消收藏店铺
     */
    function offCollect(Request $request)
    {
        $shopId = $request->post('store_id');
        $userId = ApiJwt::decodeToken($request->header('token'));
        $res = CollectStoreModel::where('user_num', $userId)->where('shop_num', $shopId)->delete();
        if ($res) {
            return ['code' => 200, 'msg' => '取消成功'];
        }
        return ['code' => 400, 'msg' => '取消失败'];
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * 创建es索引
     */
    function createIndex()
    {
        return response()->json(Es::one()->create('shop'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 分页搜索es索引中的数据
     */
    function searchInfo(Request $request)
    {
        $page = $request->post('page');
        $shopNick = $request->post('shop_nick');
        $size = 1;
        $from = ($page - 1) * $size;
        return response()->json(Es::one()->searchInfo($size, $from, $shopNick));
    }

    /**
     * @return mixed
     * 热门商品分类
     */
    function hotsType()
    {
        $data = Redis::zrevrange('one', 0, 3);
        $arr = json_decode($data[0], true);
        return $arr;
    }

    /**
     * @param Request $request
     * @return array
     * 加入购物车
     */
    function joinCart(Request $request)
    {
        $arr['shop_num'] = intval($request->post('shop_id'));
        $arr['user_num'] = ApiJwt::decodeToken($request->post('token'));
        $arr['shop_count'] = $request->post('shop_count');
        $shopPrice=ShopModel::where('shop_id',$arr['shop_num'])->value('shop_price');
        $arr['total']=$shopPrice*$arr['shop_count'];
        $data = DB::table('shop_cart')->where("user_num", $arr['user_num'])->where('shop_num', $arr['shop_num'])->value('cart_id');
        if ($data) {
             DB::table('shop_cart')->where("user_num", $arr['user_num'])->where('shop_num', $arr['shop_num'])->increment('shop_count', $arr['shop_count']);
             DB::table('shop_cart')->where("user_num", $arr['user_num'])->where('shop_num', $arr['shop_num'])->increment('total', $arr['total']);
             return ['code' => 200, 'msg' => '已加入购物车'];
        }
        $arr['shop_status'] = ShopModel::where('shop_id', $arr['shop_num'])->value('shop_status');
        $arr['created_at'] = date('Y-m-d H:i:s');
        $res = DB::table('shop_cart')->insert($arr);
        if ($res) {
            return ['code' => 200, 'msg' => '已加入购物车'];
        }
        return ['code' => 400, 'msg' => '加入失败'];
    }

    /**
     * @param Request $request
     * @return mixed
     * 获取对用用户购物车信息
     */
    function cartInfo(Request $request)
    {
        $userId = ApiJwt::decodeToken($request->get('token'));
        $data = ShopCartModel::join('shop', 'shop_num', 'shop_id')->where('user_num', $userId)->get(['shop_id', 'shop_nick', 'shop_price', 'shop_count', 'shop_logo','total'])->toArray();
       $total=[];
        foreach ($data as $k => $val) {
            $logo = explode(',', $data[$k]['shop_logo']);
            $data[$k]['shop_logo'] = $logo[0];
            array_push($total,$val['shop_price']);
        }
        $sum=array_sum($total);
        return ['code'=>200,'msg'=>$sum,'data'=>$data];
    }

    /**
     * @param Request $request
     * @return array
     * 清空购物车
     */
    function clearCart(Request $request)
    {
        $userId = ApiJwt::decodeToken($request->post('token'));
        $ids = $request->post('ids');
        $res = DB::table('shop_cart')->where('user_num', $userId)->delete();
        if ($res) {
            return ['code' => 400, 'msg' => '清除成功'];
        }
        return ['code' => 400, 'msg' => '清除失败'];
    }

}
